<template>
  <div class="dashboard-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <div class="header-icon">
          <i class="el-icon-data-board"></i>
        </div>
        <div class="header-info">
          <h1>销售仪表盘</h1>
          <p class="header-subtitle">实时数据监控与分析</p>
        </div>
      </div>
      <div class="header-controls">
        <div class="control-group">
          <label>选择日期</label>
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            @change="onDateChange"
            size="medium"
          />
        </div>
        <el-button 
          type="primary" 
                      icon="el-icon-refresh-right" 
          size="medium" 
          @click="refreshAllData"
          :loading="refreshing"
          class="refresh-btn"
        >
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 增强版概览卡片 -->
    <div class="overview-section">
      <el-row :gutter="24">
        <el-col :span="6" :xs="12" :sm="12" :md="6">
          <div class="stat-card daily-card" @click="onCardClick('daily')">
            <div class="card-decoration"></div>
            <div class="card-content">
                                            <div class="card-icon daily">
                <i class="el-icon-money"></i>
              </div>
              <div class="card-info">
                <div class="card-header">
                  <h3>今日销售额</h3>
                  <div class="trend-indicator" :class="{ positive: todaySalesChange >= 0, negative: todaySalesChange < 0 }">
                    <i :class="todaySalesChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(todaySalesChange) }}%
                  </div>
                </div>
                <p class="amount">¥{{ (dailyStats.total_amount || overview.todaySales || 0) | currency }}</p>
                <div class="card-footer">
                  <span class="count">{{ dailyStats.total_orders || overview.todayOrders || 0 }}笔订单</span>
                  <span class="avg">平均¥{{ (dailyStats.avg_order_amount || 0) | currency }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" :xs="12" :sm="12" :md="6">
          <div class="stat-card weekly-card" @click="onCardClick('weekly')">
            <div class="card-decoration"></div>
            <div class="card-content">
              <div class="card-icon weekly">
                <i class="el-icon-tickets"></i>
              </div>
              <div class="card-info">
                <div class="card-header">
                  <h3>本周销售额</h3>
                  <div class="trend-indicator" :class="{ positive: ordersChange >= 0, negative: ordersChange < 0 }">
                    <i :class="ordersChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(ordersChange) }}%
                  </div>
                </div>
                <p class="amount">¥{{ (weeklyStats.total_amount || 0) | currency }}</p>
                <div class="card-footer">
                  <span class="count">{{ weeklyStats.total_orders || 0 }}笔订单</span>
                  <span class="avg">平均¥{{ (weeklyStats.avg_order_amount || 0) | currency }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" :xs="12" :sm="12" :md="6">
          <div class="stat-card monthly-card" @click="onCardClick('monthly')">
            <div class="card-decoration"></div>
            <div class="card-content">
              <div class="card-icon monthly">
                <i class="el-icon-data-line"></i>
              </div>
              <div class="card-info">
                <div class="card-header">
                  <h3>本月销售额</h3>
                  <div class="trend-indicator" :class="{ positive: membersChange >= 0, negative: membersChange < 0 }">
                    <i :class="membersChange >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(membersChange) }}%
                  </div>
                </div>
                <p class="amount">¥{{ (monthlyStats.total_amount || 0) | currency }}</p>
                <div class="card-footer">
                  <span class="count">{{ monthlyStats.total_orders || 0 }}笔订单</span>
                  <span class="avg">平均¥{{ (monthlyStats.avg_order_amount || 0) | currency }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6" :xs="12" :sm="12" :md="6">
          <div class="stat-card products-card" @click="onCardClick('products')">
            <div class="card-decoration"></div>
            <div class="card-content">
              <div class="card-icon products">
                <i class="el-icon-shopping-bag-1"></i>
              </div>
              <div class="card-info">
                <div class="card-header">
                  <h3>商品统计</h3>
                  <div class="trend-indicator positive">
                    <i class="el-icon-star-on"></i>
                    转化率
                  </div>
                </div>
                <p class="amount">{{ comprehensiveStats.total_products || 0 }}</p>
                <div class="card-footer">
                  <span class="count">总商品数</span>
                  <span class="avg">{{ overview.conversion || 0 }}%</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="24">
        <!-- 销售趋势图 -->
        <el-col :span="12" :xs="24" :sm="24" :md="12">
          <div class="chart-card trend-card">
            <div class="card-header">
              <div class="header-left">
                <div class="chart-icon">
                  <i class="el-icon-data-analysis"></i>
                </div>
                <div class="header-info">
                  <h3>销售趋势分析</h3>
                  <p>实时销售数据变化趋势</p>
                </div>
              </div>
              <div class="header-controls">
                <el-radio-group v-model="trendPeriod" size="small" @change="onTrendPeriodChange">
                  <el-radio-button label="week">近7天</el-radio-button>
                  <el-radio-button label="month">近30天</el-radio-button>
                  <el-radio-button label="quarter">近3个月</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="chart-content" v-loading="trendLoading">
              <v-chart 
                :options="enhancedSalesTrendOptions" 
                style="height: 380px; width: 100%;"
              />
            </div>
          </div>
        </el-col>

        <!-- 热销商品排行 -->
        <el-col :span="12" :xs="24" :sm="24" :md="12">
          <div class="chart-card products-chart-card pie-chart-container">
            <div class="card-header compact-header">
              <div class="header-left">
                <div class="chart-icon">
                  <i class="el-icon-data-board"></i>
                </div>
                <div class="header-info">
                  <h3>热销商品排行</h3>
                  <p>商品销售量分布</p>
                </div>
              </div>
              <div class="header-controls">
                <el-select v-model="productPeriod" size="small" @change="onProductPeriodChange">
                  <el-option label="今日" value="today"></el-option>
                  <el-option label="本周" value="week"></el-option>
                  <el-option label="本月" value="month"></el-option>
                  <el-option label="本季度" value="quarter"></el-option>
                </el-select>
              </div>
            </div>
            <div class="chart-content pie-chart-content" v-loading="productsLoading">
              <v-chart 
                :options="topProductsPieOptions" 
                style="height: 380px; width: 100%;"
                v-if="!productsLoading"
              />
              <div v-else style="height: 380px; display: flex; align-items: center; justify-content: center;">
                <i class="el-icon-loading loading-spin" style="font-size: 24px; color: #409EFF;"></i>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="charts-section">
      <el-row :gutter="24">
        <el-col :span="12" :xs="24" :sm="24" :md="12">
          <div class="chart-card rank-card">
            <div class="card-header">
              <div class="header-left">
                <div class="chart-icon">
                  <i class="el-icon-goods"></i>
                </div>
                <div class="header-info">
                  <h3>商品销售排行</h3>
                  <p>热门商品销量统计</p>
                </div>
              </div>
            </div>
            <div class="chart-content">
              <v-chart :options="productRankOptions" style="height: 300px; width: 100%;" />
            </div>
          </div>
        </el-col>
        <el-col :span="12" :xs="24" :sm="24" :md="12">
          <div class="chart-card rank-card">
            <div class="card-header">
              <div class="header-left">
                <div class="chart-icon">
                  <i class="el-icon-s-custom"></i>
                </div>
                <div class="header-info">
                  <h3>销售员业绩排行</h3>
                  <p>销售团队表现分析</p>
                </div>
              </div>
            </div>
            <div class="chart-content">
              <v-chart :options="salespersonRankOptions" style="height: 300px; width: 100%;" />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 详细数据表格 -->
    <div class="table-section">
      <div class="table-card">
        <div class="card-header">
          <div class="header-left">
            <div class="chart-icon">
              <i class="el-icon-tickets"></i>
            </div>
            <div class="header-info">
              <h3>热销商品详情</h3>
              <p>商品销售详细数据统计</p>
            </div>
          </div>
          <div class="header-controls">
            <el-button 
              type="primary" 
              icon="el-icon-download"
              @click="exportData"
              size="medium"
              plain
            >
              导出数据
            </el-button>
          </div>
        </div>
        <div class="table-content">
          <el-table 
            :data="topProductsList" 
            :loading="productsLoading"
            stripe
            style="width: 100%"
            max-height="450"
            :header-cell-style="{
              background: '#f8f9fa',
              color: '#606266',
              fontWeight: '500'
            }"
          >
            <el-table-column prop="rank" label="排名" width="80" align="center">
              <template slot-scope="scope">
                <div class="rank-badge" :class="`rank-${scope.row.rank <= 3 ? 'top' : scope.row.rank <= 10 ? 'mid' : 'low'}`">
                  <i v-if="scope.row.rank === 1" class="el-icon-trophy-1"></i>
                  <i v-else-if="scope.row.rank === 2" class="el-icon-trophy"></i>
                  <i v-else-if="scope.row.rank === 3" class="el-icon-medal-1"></i>
                  <span v-else>{{ scope.row.rank }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称" min-width="220">
              <template slot-scope="scope">
                <div class="product-info">
                  <div class="product-name">{{ scope.row.product_name }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales_quantity" label="销售数量" width="120" align="right">
              <template slot-scope="scope">
                <div class="quantity-info">
                  <span class="quantity">{{ scope.row.sales_quantity | numberFormat }}</span>
                  <span class="unit">件</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales_amount" label="销售金额" width="150" align="right">
              <template slot-scope="scope">
                <div class="amount-info">
                  <span class="amount">¥{{ scope.row.sales_amount | currency }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="percentage" label="占比" width="120" align="right">
              <template slot-scope="scope">
                <div class="percentage-info">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: (scope.row.percentage * 100) + '%' }"></div>
                  </div>
                  <span class="percentage">{{ (scope.row.percentage * 100).toFixed(1) }}%</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Dashboard',
  filters: {
    currency(value) {
      if (!value) return '0.00'
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    numberFormat(value) {
      if (!value) return '0'
      return parseInt(value).toLocaleString('zh-CN')
    }
  },
  data() {
    return {
      loading: false,
      refreshing: false,
      selectedDate: new Date().toISOString().split('T')[0],
      trendDays: 7,
      trendPeriod: 'month',
      productPeriod: 'month',
      
      // 原有数据
      overview: {
        todaySales: 0,
        yesterdaySales: 0,
        todayOrders: 0,
        yesterdayOrders: 0,
        todayMembers: 0,
        yesterdayMembers: 0,
        conversion: 0,
        yesterdayConversion: 0
      },
      salesTrend: {
        dates: [],
        sales: [],
        orders: []
      },
      salesComposition: [],
      productRank: [],
      salespersonRank: [],
      
      // 新增统计数据
      dailyStats: {},
      weeklyStats: {},
      monthlyStats: {},
      comprehensiveStats: {},
      salesCurveData: [],
      topProductsList: [
        { rank: 1, product_name: 'iPhone 15 Pro', sales_quantity: 156, sales_amount: 156000, percentage: 0.25 },
        { rank: 2, product_name: 'MacBook Pro M3', sales_quantity: 89, sales_amount: 178000, percentage: 0.18 },
        { rank: 3, product_name: 'iPad Air', sales_quantity: 134, sales_amount: 80400, percentage: 0.15 },
        { rank: 4, product_name: 'Apple Watch S9', sales_quantity: 203, sales_amount: 81200, percentage: 0.12 },
        { rank: 5, product_name: 'AirPods Pro 2', sales_quantity: 267, sales_amount: 53400, percentage: 0.10 }
      ],
      
      // 加载状态
      trendLoading: false,
      productsLoading: false
    }
  },
  computed: {
    // 计算同比变化
    todaySalesChange() {
      return this.calculateChange(
        this.dailyStats.total_amount || this.overview.todaySales, 
        this.overview.yesterdaySales
      )
    },
    ordersChange() {
      return this.calculateChange(this.overview.todayOrders, this.overview.yesterdayOrders)
    },
    membersChange() {
      return this.calculateChange(this.overview.todayMembers, this.overview.yesterdayMembers)
    },
    conversionChange() {
      return this.calculateChange(this.overview.conversion, this.overview.yesterdayConversion)
    },
    // ECharts配置项
    enhancedSalesTrendOptions() {
      const data = this.salesCurveData.length > 0 ? this.salesCurveData : this.salesTrend
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: 'transparent',
          textStyle: {
            color: '#fff',
            fontSize: 12
          }
        },
        legend: {
          data: ['销售额', '订单数'],
          top: '3%',
          left: 'center',
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '15%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.dates || data.map(item => item.date || item.period),
          axisLabel: {
            fontSize: 11,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e8e8e8'
            }
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            position: 'left',
            nameTextStyle: {
              fontSize: 11,
              color: '#666'
            },
            axisLabel: {
              formatter: '¥{value}',
              fontSize: 10,
              color: '#666'
            },
            axisLine: {
              lineStyle: {
                color: '#e8e8e8'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f5f5f5'
              }
            }
          },
          {
            type: 'value',
            name: '订单数',
            position: 'right',
            nameTextStyle: {
              fontSize: 11,
              color: '#666'
            },
            axisLabel: {
              formatter: '{value}笔',
              fontSize: 10,
              color: '#666'
            },
            axisLine: {
              lineStyle: {
                color: '#e8e8e8'
              }
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            data: data.sales || data.map(item => item.total_amount || 0),
            smooth: true,
            yAxisIndex: 0,
            lineStyle: {
              color: '#409EFF',
              width: 3
            },
            symbol: 'circle',
            symbolSize: 6,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(64, 158, 255, 0.3)'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.05)'
                }]
              }
            }
          },
          {
            name: '订单数',
            type: 'line',
            data: data.orders || data.map(item => item.total_orders || 0),
            smooth: true,
            yAxisIndex: 1,
            lineStyle: {
              color: '#67C23A',
              width: 3
            },
            symbol: 'circle',
            symbolSize: 6
          }
        ]
      }
    },
    
    // 热销商品饼图
    topProductsPieOptions() {
      const data = this.topProductsList.slice(0, 8).map((item, index) => ({
        value: item.sales_quantity || 0,
        name: item.product_name || `商品${index + 1}`,
        itemStyle: {
          color: this.getPieChartColors()[index] || '#409EFF'
        }
      }))
      
      console.log('饼图数据:', data)
      
      return {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: 'transparent',
          textStyle: {
            color: '#fff',
            fontSize: 12
          }
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          bottom: '3%',
          left: 'center',
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 8,
          padding: [5, 10],
          textStyle: {
            fontSize: 11,
            color: '#666'
          },
          formatter: function(name) {
            return name.length > 8 ? name.substring(0, 8) + '...' : name
          }
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '3%',
          bottom: '15%',
          containLabel: true
        },
        series: [
          {
            type: 'pie',
            radius: ['35%', '65%'],
            center: ['50%', '45%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside',
              fontSize: 10,
              color: '#666',
              distanceToLabelLine: 5,
              formatter: function(params) {
                if (params.percent < 5) {
                  return ''
                }
                return `${params.percent}%`
              }
            },
            labelLine: {
              show: true,
              length: 8,
              length2: 8,
              smooth: 0.2,
              lineStyle: {
                color: '#ccc',
                width: 1
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              label: {
                show: true,
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            data: data
          }
        ]
      }
    },
    salesCompositionOptions() {
      return {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            data: this.salesComposition
          }
        ]
      }
    },
    productRankOptions() {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: 'transparent',
          textStyle: {
            color: '#fff',
            fontSize: 12
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '8%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 11,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e8e8e8'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: this.productRank.map(item => item.name),
          axisLabel: {
            fontSize: 11,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e8e8e8'
            }
          }
        },
        series: [
          {
            type: 'bar',
            data: this.productRank.map(item => item.value),
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [{
                  offset: 0, color: '#409EFF'
                }, {
                  offset: 1, color: '#36cfc9'
                }]
              },
              borderRadius: [0, 4, 4, 0]
            },
            barWidth: '60%'
          }
        ]
      }
    },
    salespersonRankOptions() {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: 'transparent',
          textStyle: {
            color: '#fff',
            fontSize: 12
          }
        },
        legend: {
          data: ['销售额', '订单数'],
          top: '3%',
          left: 'center',
          textStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '15%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 11,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e8e8e8'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5'
            }
          }
        },
        yAxis: {
          type: 'category',
          data: this.salespersonRank.map(item => item.name),
          axisLabel: {
            fontSize: 11,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#e8e8e8'
            }
          }
        },
        series: [
          {
            name: '销售额',
            type: 'bar',
            data: this.salespersonRank.map(item => item.sales),
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [{
                  offset: 0, color: '#409EFF'
                }, {
                  offset: 1, color: '#36cfc9'
                }]
              },
              borderRadius: [0, 4, 4, 0]
            },
            barWidth: '45%'
          },
          {
            name: '订单数',
            type: 'bar',
            data: this.salespersonRank.map(item => item.orders),
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [{
                  offset: 0, color: '#67C23A'
                }, {
                  offset: 1, color: '#95de64'
                }]
              },
              borderRadius: [0, 4, 4, 0]
            },
            barWidth: '45%'
          }
        ]
      }
    }
  },
  watch: {
    trendDays: {
      handler(val) {
        this.fetchSalesTrend(val)
      }
    }
  },
  created() {
    this.fetchAllData()
  },
  methods: {
    calculateChange(today, yesterday) {
      if (!yesterday) return 0
      return Math.round(((today - yesterday) / yesterday) * 100)
    },
    
    async fetchAllData() {
      this.loading = true
      try {
        await this.fetchData()
      } catch (error) {
        console.error('获取数据失败：', error)
        this.$message.error(error.response?.data?.detail || '数据加载失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    async fetchData() {
      this.loading = true
      try {
        // 获取概览数据
        const overviewRes = await this.$http.get('/dashboard/overview')
        this.overview = overviewRes.data

        // 获取销售趋势
        const trendRes = await this.$http.get('/dashboard/sales-trend', {
          params: {
            days: this.trendPeriod === 'week' ? 7 : this.trendPeriod === 'month' ? 30 : 60
          }
        })
        this.salesTrend = trendRes.data

        // 获取销售构成
        const compositionRes = await this.$http.get('/dashboard/sales-composition')
        this.salesComposition = compositionRes.data

        // 获取商品排行
        const productRes = await this.$http.get('/dashboard/product-rank', {
          params: { limit: 10 }
        })
        this.productRank = productRes.data

        // 获取销售员排行
        const salespersonRes = await this.$http.get('/dashboard/salesperson-rank', {
          params: { limit: 10 }
        })
        this.salespersonRank = salespersonRes.data

        // 获取日销售统计
        const dailyRes = await this.$http.get('/dashboard/daily-stats', {
          params: { date: this.selectedDate }
        })
        this.dailyStats = dailyRes.data

        // 获取周销售统计
        const weeklyRes = await this.$http.get('/dashboard/weekly-stats')
        this.weeklyStats = weeklyRes.data

        // 获取月销售统计
        const monthlyRes = await this.$http.get('/dashboard/monthly-stats')
        this.monthlyStats = monthlyRes.data

        // 获取综合统计
        const comprehensiveRes = await this.$http.get('/dashboard/comprehensive-stats')
        this.comprehensiveStats = comprehensiveRes.data

        // 获取销售曲线
        const curveRes = await this.$http.get('/dashboard/sales-curve', {
          params: {
            period: this.trendPeriod,
            interval: 'day'
          }
        })
        this.salesCurveData = curveRes.data

        // 获取热销商品
        const topProductsRes = await this.$http.get('/dashboard/top-products', {
          params: {
            period: this.productPeriod,
            limit: 20
          }
        })
        this.topProductsList = topProductsRes.data.map((item, index) => ({
          ...item,
          rank: index + 1
        }))

      } catch (error) {
        console.error('获取数据失败：', error)
        this.$message.error(error.response?.data?.detail || '数据加载失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    async fetchSalesTrend(days) {
      try {
        const res = await this.$http.get('/dashboard/sales-trend', {
          params: { days }
        })
        this.salesTrend = res.data || { dates: [], sales: [], orders: [] }
      } catch (error) {
        console.error('获取销售趋势数据失败：', error)
      }
    },
    
    // 事件处理方法
    onDateChange() {
      this.fetchData()
    },
    
    onTrendPeriodChange() {
      this.fetchData()
    },
    
    onProductPeriodChange() {
      this.fetchData()
    },
    
    async refreshAllData() {
      this.refreshing = true
      try {
        await this.fetchData()
        this.$message.success('数据刷新成功')
      } catch (error) {
        this.$message.error('数据刷新失败')
      } finally {
        this.refreshing = false
      }
    },
    
    exportData() {
      const csvContent = this.generateCSV()
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `热销商品排行_${new Date().toISOString().split('T')[0]}.csv`
      link.click()
    },
    
    onCardClick(cardType) {
      console.log(`点击了${cardType}卡片`)
      // 可以根据需要添加卡片点击逻辑，比如跳转到详情页面
    },
    
    generateCSV() {
      const headers = ['排名', '商品名称', '销售数量', '销售金额', '占比']
      const rows = this.topProductsList.map(item => [
        item.rank,
        item.product_name,
        item.sales_quantity,
        item.sales_amount,
        `${(item.percentage * 100).toFixed(2)}%`
      ])
      
      return [headers, ...rows].map(row => row.join(',')).join('\n')
    },
    
    generateMockSalesCurve() {
      const days = this.trendPeriod === '7' ? 7 : this.trendPeriod === '30' ? 30 : 90
      const data = []
      const now = new Date()
      
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
        const dateStr = date.toISOString().split('T')[0]
        const amount = Math.floor(Math.random() * 50000) + 10000
        const orders = Math.floor(Math.random() * 50) + 10
        
        data.push({
          date: dateStr,
          amount: amount,
          order_count: orders
        })
      }
      
      return data
    },
    
    getPieChartColors() {
      return [
        '#409EFF', // 蓝色
        '#67C23A', // 绿色
        '#E6A23C', // 橙色
        '#F56C6C', // 红色
        '#909399', // 灰色
        '#9C27B0', // 紫色
        '#FF9800', // 深橙色
        '#4CAF50'  // 深绿色
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32px;
    padding: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
    color: white;
    
    .header-left {
      display: flex;
      align-items: center;
      
      .header-icon {
        width: 64px;
        height: 64px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;
        
        &:hover {
          transform: scale(1.1);
          background: rgba(255, 255, 255, 0.3);
        }
        
        i {
          font-size: 28px;
          color: white;
          transition: all 0.3s ease;
        }
      }
      
      .header-info {
        h1 {
          margin: 0 0 8px 0;
          font-size: 28px;
          font-weight: 600;
          color: white;
        }
        
        .header-subtitle {
          margin: 0;
          font-size: 14px;
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
    
    .header-controls {
      display: flex;
      align-items: center;
      gap: 20px;
      
      .control-group {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        
        label {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.8);
          margin-bottom: 8px;
        }
      }
      
      .refresh-btn {
        height: 40px;
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        backdrop-filter: blur(10px);
        
        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }
      }
    }
  }
  
  .overview-section {
    margin-bottom: 32px;
    
    .stat-card {
      background: white;
      border-radius: 16px;
      padding: 24px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 40px rgba(0, 0, 0, 0.12);
      }
      
      .card-decoration {
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100px;
        height: 100px;
        opacity: 0.1;
        border-radius: 50%;
        transition: all 0.3s ease;
      }
      
      &.daily-card .card-decoration {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.weekly-card .card-decoration {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.monthly-card .card-decoration {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.products-card .card-decoration {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
      
      .card-content {
        display: flex;
        align-items: flex-start;
        position: relative;
        z-index: 1;
        
        .card-icon {
          width: 56px;
          height: 56px;
          border-radius: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20px;
          flex-shrink: 0;
          transition: all 0.3s ease;
          position: relative;
          overflow: hidden;
          
          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
          }
          
          &:hover::before {
            left: 100%;
          }
          
          &:hover {
            transform: translateY(-2px) scale(1.05);
          }
          
          i {
            font-size: 24px;
            color: white;
            transition: all 0.3s ease;
            z-index: 1;
            
            &:hover {
              transform: rotate(5deg);
            }
          }
          
          &.daily {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
            
            &:hover {
              background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
              box-shadow: 0 8px 30px rgba(102, 126, 234, 0.6);
            }
          }
          
          &.weekly {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            box-shadow: 0 4px 20px rgba(240, 147, 251, 0.4);
            
            &:hover {
              background: linear-gradient(135deg, #ee7ff0 0%, #f34560 100%);
              box-shadow: 0 8px 30px rgba(240, 147, 251, 0.6);
            }
          }
          
          &.monthly {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            box-shadow: 0 4px 20px rgba(79, 172, 254, 0.4);
            
            &:hover {
              background: linear-gradient(135deg, #3d9afc 0%, #00e6fc 100%);
              box-shadow: 0 8px 30px rgba(79, 172, 254, 0.6);
            }
          }
          
          &.products {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            box-shadow: 0 4px 20px rgba(67, 233, 123, 0.4);
            
            &:hover {
              background: linear-gradient(135deg, #31e069 0%, #26f7c5 100%);
              box-shadow: 0 8px 30px rgba(67, 233, 123, 0.6);
            }
          }
        }
        
        .card-info {
          flex: 1;
          
          .card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            
            h3 {
              margin: 0;
              font-size: 14px;
              color: #8c8c8c;
              font-weight: 500;
            }
            
            .trend-indicator {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 12px;
              font-weight: 600;
              padding: 4px 8px;
              border-radius: 12px;
              transition: all 0.3s ease;
              
              &:hover {
                transform: scale(1.05);
              }
              
              &.positive {
                color: #52c41a;
                background: rgba(82, 196, 26, 0.1);
                
                i {
                  animation: bounce-up 2s infinite;
                }
              }
              
              &.negative {
                color: #ff4d4f;
                background: rgba(255, 77, 79, 0.1);
                
                i {
                  animation: bounce-down 2s infinite;
                }
              }
              
              i {
                font-size: 10px;
                transition: all 0.3s ease;
              }
            }
          }
          
          .amount {
            margin: 0 0 12px 0;
            font-size: 20px;
            font-weight: 700;
            color: #262626;
            line-height: 1;
          }
          
          .card-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .count {
              font-size: 10px;
              color: #8c8c8c;
            }
            
            .avg {
              font-size: 10px;
              color: #1890ff;
              font-weight: 500;
            }
          }
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 32px;
    
    .chart-card {
      background: white;
      border-radius: 16px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      overflow: hidden;
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 8px 40px rgba(0, 0, 0, 0.12);
      }
      
      .card-header {
        padding: 24px 24px 0 24px;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20px;
        
        .header-left {
          display: flex;
          align-items: flex-start;
          
          .chart-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16px;
            flex-shrink: 0;
            transition: all 0.3s ease;
            position: relative;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            
            &::after {
              content: '';
              position: absolute;
              top: 50%;
              left: 50%;
              width: 0;
              height: 0;
              background: rgba(255, 255, 255, 0.2);
              border-radius: 50%;
              transform: translate(-50%, -50%);
              transition: all 0.3s ease;
            }
            
            &:hover {
              transform: translateY(-2px) scale(1.1);
              box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
              
              &::after {
                width: 100%;
                height: 100%;
              }
            }
            
            i {
              font-size: 20px;
              color: white;
              transition: all 0.3s ease;
              z-index: 1;
              
              &:hover {
                transform: scale(1.2);
              }
            }
          }
          
          .header-info {
            h3 {
              margin: 0 0 4px 0;
              font-size: 18px;
              font-weight: 600;
              color: #262626;
            }
            
            p {
              margin: 0;
              font-size: 13px;
              color: #8c8c8c;
            }
          }
        }
        
        .header-controls {
          flex-shrink: 0;
        }
      }
      
      .chart-content {
        padding: 0 20px 20px 20px;
        
        // 确保图表容器适应卡片
        .echarts {
          width: 100% !important;
          height: 100% !important;
        }
      }
      
      // 饼图专用样式
      &.pie-chart-container {
        .compact-header {
          padding: 20px 20px 0 20px;
          margin-bottom: 12px;
        }
        
        .pie-chart-content {
          padding: 0 12px 16px 12px;
          
          .echarts {
            width: 100% !important;
            height: 100% !important;
          }
        }
      }
      
      // 排行榜卡片样式
      &.rank-card {
        .chart-content {
          padding: 0 16px 16px 16px;
        }
      }
    }
  }
  
  .table-section {
    .table-card {
      background: white;
      border-radius: 16px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      overflow: hidden;
      
      .card-header {
        padding: 24px;
        background: #fafafa;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-left {
          display: flex;
          align-items: center;
          
          .chart-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16px;
            
            i {
              font-size: 20px;
              color: white;
            }
          }
          
          .header-info {
            h3 {
              margin: 0 0 4px 0;
              font-size: 18px;
              font-weight: 600;
              color: #262626;
            }
            
            p {
              margin: 0;
              font-size: 13px;
              color: #8c8c8c;
            }
          }
        }
      }
      
      .table-content {
        padding: 0;
        
        .rank-badge {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 32px;
          height: 32px;
          border-radius: 8px;
          font-weight: 600;
          font-size: 14px;
          transition: all 0.3s ease;
          position: relative;
          
          &:hover {
            transform: scale(1.1);
          }
          
          &.rank-top {
            background: linear-gradient(135deg, #faad14 0%, #fa8c16 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(250, 173, 20, 0.4);
            animation: glow 2s ease-in-out infinite alternate;
            
            i {
              font-size: 16px;
              animation: pulse 2s infinite;
            }
          }
          
          &.rank-mid {
            background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
            
            &:hover {
              box-shadow: 0 6px 20px rgba(82, 196, 26, 0.5);
            }
          }
          
          &.rank-low {
            background: #f5f5f5;
            color: #8c8c8c;
            
            &:hover {
              background: #e6e6e6;
              color: #666;
            }
          }
        }
        
        .product-info {
          .product-name {
            font-weight: 500;
            color: #262626;
            font-size: 14px;
          }
        }
        
        .quantity-info {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 4px;
          
          .quantity {
            font-weight: 600;
            color: #262626;
          }
          
          .unit {
            font-size: 12px;
            color: #8c8c8c;
          }
        }
        
        .amount-info {
          .amount {
            font-weight: 600;
            color: #1890ff;
            font-size: 14px;
          }
        }
        
        .percentage-info {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          gap: 4px;
          
          .progress-bar {
            width: 60px;
            height: 6px;
            background: #f5f5f5;
            border-radius: 3px;
            overflow: hidden;
            
            .progress-fill {
              height: 100%;
              background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
              transition: width 0.3s ease;
            }
          }
          
          .percentage {
            font-size: 12px;
            font-weight: 600;
            color: #1890ff;
          }
        }
      }
    }
  }
}

// 动画定义
@keyframes bounce-up {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-4px);
  }
  60% {
    transform: translateY(-2px);
  }
}

@keyframes bounce-down {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(4px);
  }
  60% {
    transform: translateY(2px);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes glow {
  from {
    box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
  }
  to {
    box-shadow: 0 0 20px rgba(102, 126, 234, 0.6);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 加载动画
.loading-spin {
  animation: spin 1s linear infinite;
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      gap: 20px;
      text-align: center;
      
      .header-controls {
        flex-direction: column;
        gap: 12px;
        width: 100%;
        
        .control-group {
          align-items: center;
        }
      }
    }
    
    .charts-section {
      .chart-card {
        .card-header {
          padding: 16px 16px 0 16px;
          margin-bottom: 12px;
          
          .header-left {
            flex-direction: row;
            align-items: center;
            
            .chart-icon {
              width: 40px;
              height: 40px;
              margin-right: 12px;
              
              i {
                font-size: 18px;
              }
            }
            
            .header-info {
              h3 {
                font-size: 16px;
              }
              
              p {
                font-size: 12px;
              }
            }
          }
        }
        
        .chart-content {
          padding: 0 12px 16px 12px;
        }
        
        &.pie-chart-container {
          .pie-chart-content {
            padding: 0 8px 12px 8px;
          }
        }
      }
    }
    
    .overview-section {
      .stat-card {
        margin-bottom: 16px;
        
        .card-content {
          .amount {
            font-size: 24px;
          }
        }
      }
    }
    
    .charts-section {
      .chart-card {
        margin-bottom: 20px;
        
        .card-header {
          flex-direction: column;
          gap: 16px;
          
          .header-controls {
            width: 100%;
          }
        }
      }
    }
  }
}

// 深色模式支持（可选）
@media (prefers-color-scheme: dark) {
  .dashboard-container {
    background: #141414;
    
    .stat-card,
    .chart-card,
    .table-card {
      background: #1f1f1f;
      color: #ffffff;
      
      .card-header {
        background: #262626;
      }
    }
  }
}
</style> 